package com.sdx.common.utils;

import org.bouncycastle.jce.provider.BouncyCastleProvider;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.security.Security;
import java.util.Base64;

/**
 * @ClassName EncryptUtil
 * @Description: 加密和解密
 * @author: tanbaocai
 * @date: 2018/9/29 14:42
 */
public class EncryptUtil {
	public static final String AES_ALGORITHM = "AES/ECB/PKCS7Padding";
	public static final String CHARSET = "UTF-8";
	private static boolean aesInitialized = false;

	public static String aesEncrypt(String src,String key) throws Exception {
		Cipher cipher = getAesCipher(key,true);
		byte[] enBytes = cipher.doFinal(src.getBytes(CHARSET));
		String result = Base64.getEncoder().encodeToString(enBytes);
		return result;
	}

	public static String aesDecrypt(byte[] srcBytes,String key) throws Exception {
		Cipher cipher = getAesCipher(key,false);
		byte[] deBytes = cipher.doFinal(srcBytes);
		return new String(deBytes,CHARSET);
	}

	private static Cipher getAesCipher(String key,boolean encrypt) throws Exception {
		initAesProvider();
		Cipher cipher = Cipher.getInstance(AES_ALGORITHM,"BC");
		SecretKeySpec keySpec = new SecretKeySpec(key.getBytes(CHARSET),"AES");
		int mode = encrypt?Cipher.ENCRYPT_MODE:Cipher.DECRYPT_MODE;
		cipher.init(mode,keySpec);
		return cipher;
	}

	public synchronized static void initAesProvider() {
		if (aesInitialized) {
			return;
		}
		Security.addProvider(new BouncyCastleProvider());
		aesInitialized = true;
	}

	public static void main(String[] args) throws Exception {
		String src = "asdgasdgasdge4sdg";
		String key = MD5.MD5Encode("lwrkjghlkajsdlkjglkjasdgsdg");
		String encode = aesEncrypt(src,key);
		System.out.println(encode);
		byte[] encodeBytes = Base64.getDecoder().decode(encode);
		String decode = aesDecrypt(encodeBytes,key);
		System.out.println(decode);
		System.out.println(decode.equals(src));
	}
}
